package com.letv.whatslive.mongo.dao;

import com.letv.whatslive.model.VersionControl;
import com.letv.whatslive.model.convert.VersionControlConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

/**
 * Created by wangjian7 on 2015/11/12.
 */
@Repository
public class VersionControlDAO extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(UserDAO.class);

    protected String collectionName = "versionControl";

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    /**
     * 根据type获取获取版本控制信息
     * @param type
     * @return
     */
    public VersionControl getVersionCrotrolByType(String type){
        try {
            BasicDBObject query = new BasicDBObject();
            query.put("type", type);
            DBObject dbObject = this.dbCollection.findOne(query);
            return VersionControlConvert.castDBObjectToVersionCrotrol(dbObject);
        } catch (Exception e) {
            logger.error("getVersionControlByType error! type:", e);
            return null;
        }
    }

    /**
     * 根据type更新版本控制信息
     * @param type
     */
    public void updateVersionByType(String type){
        DBObject query = new BasicDBObject("type", type);
        DBObject dbo = this.dbCollection.findOne(query);
        if (dbo == null) {//insert
            VersionControl versionControl = new VersionControl();
            versionControl.setId(this.getAutoIncrementId());
            versionControl.setType(type);
            versionControl.setUpdateTime(System.currentTimeMillis());
            this.dbCollection.save(VersionControlConvert.castVersionCrotrolToDBObject(versionControl));
        } else {
            dbo.put("updateTime", System.currentTimeMillis());
            this.dbCollection.update(query, dbo);
        }
    }

}
